<?php

namespace app\server\notice\model;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\model\Config;

/**
 * 发送短信模型
 *
 * Class Sms
 * @package app\server\notice\model
 */
class Sms
{

    /**
     * 发送短信
     *
     * @param int|string $mobile 电话号码
     * @param string $signName 短信签名
     * @param string $templateCode 模板code
     * @param array $params 参选参数 ['code' => 1234]
     * @return boolean|string
     * @throws ClientException
     */
    public function index($mobile, string $signName, string $templateCode, array $params = [])
    {
        $keyId = Config::get('access_keyid', 'sms');
        $secret = Config::get('access_secret', 'sms');
        AlibabaCloud::accessKeyClient($keyId, $secret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => $signName,
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => json_encode($params)
                    ],
                ])
                ->request();

            $result = $result->toArray();

            if (strtolower($result['Message']) == 'ok') {
                return true;
            }
            return $result['Message'];

        } catch (ClientException $exception) {
            return $exception->getErrorMessage();
        } catch (ServerException $exception) {
            return $exception->getErrorMessage();
        }
    }
}